package wildcard.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import wildcard.database.DBAccess;

public class LoginServlet extends HttpServlet {
	private static final String VALUE_USER_ANDORID = "Andorid";
	private static final String VALUE_USER_WINDOWS = "Windows";
	private static final String KEY_USER_OS = "OS";
	private static final String KEY_LOGIN_USER = "LoginUser";
	private static final String DATABASE_LOGINID = "LOGIN";
	private static final String DATABASE_PASSWORD = "wildcard";

	private static final String KEY_USER_AGENT = "user-agent";

	// 遷移先のjspまたは、サーブレット(0:正常処理、1:エラー処理)
	private static final String[] JSP_TRANSITION_WINDOWS = {
			"maintenance_menu.jsp", "login.jsp" };
	private static final String[] JSP_TRANSITION_ANDROID = {
			"mainactivity/", "login/" };

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		ArrayList<ArrayList<String>> resultList = null;
		ArrayList<String> parameters = null;

		req.setCharacterEncoding("UTF-8");
		Connection con = null;

		// アクセスしてきたOSとIDをチェックするための文字列パターン
		String agent = req.getHeader(KEY_USER_AGENT);
		String regex = "^*Windows.*$";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(agent);

		// ログイン画面から入力されたIDとパスワード
		String loginId = req.getParameter("id");
		String loginPassword = req.getParameter("pw");
		String sqlCommand = req.getParameter("sql");

		try {
			// SQL文の取得
			parameters = new ArrayList<String>();
			parameters.add(sqlCommand);
			resultList = DBAccess.executeSelect(DATABASE_LOGINID, DATABASE_PASSWORD,
					DBAccess.SQL_SELECT_COMMAND, parameters);

			String sqlLogin = resultList.get(1).get(0);

			// 外部入力用パラメータリストへ格納する
			parameters.clear();
			parameters.add(loginId);
			parameters.add(loginPassword);

			// 出力結果
			resultList = DBAccess.executeSelect(DATABASE_LOGINID, DATABASE_PASSWORD,
					sqlLogin, parameters);
			RequestDispatcher dispatcher;
			int resultCountId = Integer.parseInt(resultList.get(1).get(0));

			// OSごとに遷移先を切り替える
			if (m.find()) {
				// Windowsの場合
				System.out.println("Windowsからのアクセスです");
				req.setAttribute(KEY_USER_OS, VALUE_USER_WINDOWS);

				req.setAttribute("ip", req.getRemoteAddr());

				dispatcher = transition(req, resp, resultCountId, loginId,
						loginPassword, "", JSP_TRANSITION_WINDOWS);
				dispatcher.forward(req, resp);

			} else {
				// Androidの場合
				System.out.println("Androidからのアクセスです");

				req.setAttribute(KEY_USER_OS, VALUE_USER_ANDORID);

				req.setAttribute("ip", req.getRemoteAddr());
				String responceUrlHost = "WILDCARD://" + req.getRemoteAddr() + ":8080/wildcard/";

				dispatcher = transition(req, resp, resultCountId, loginId,
						loginPassword, responceUrlHost, JSP_TRANSITION_ANDROID);
				dispatcher.forward(req, resp);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		finally {
			try {
				if (con != null) {
					con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	private RequestDispatcher transition(HttpServletRequest req,
			HttpServletResponse resp, int resultCountId, String loginId,
			String loginPassword, String urlhost, String[] transitions)
			throws ServletException, IOException {
		RequestDispatcher dispatcher;

		if (resultCountId == 1) {
			// 正常処理
			resp.setStatus(HttpServletResponse.SC_OK);

			// BeanにIDとパスワードを詰めてセッションに登録する
			LoginBean loginBean = new LoginBean(loginId, loginPassword);

			// 遷移処理を行う
			HttpSession session = req.getSession();
			session.setAttribute(KEY_LOGIN_USER, loginBean);
			dispatcher = req.getRequestDispatcher(urlhost + transitions[0]);

		} else {
			// エラー処理
			resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);

			// 元の画面に戻る
			dispatcher = req.getRequestDispatcher(urlhost + transitions[1]);
		}

		return dispatcher;
	}
}
